<template>
  <div class="about">
    <ul>
      <li v-for="item in msgList" :key='item.id'>
        <p>
          <span>{{item.user}}</span>
          <span>{{new Date(item.dateTime)}}</span>
        </p>
        <p>消息:{{item.msg}}</p>
      </li>
    </ul>
   <input type="text" placeholder="请输入消息" v-model="msg">
   <button @click="sendMsg">发送消息</button>
  </div>
</template>
<script>
const ws = new WebSocket('ws://localhost:8080')
export default {
  data () {
    return {
      msg:"",
      username:"",
      msgList:[]
    }
  },
  mounted () {
    this.username = localStorage.getItem('username')
    if(!this.username){
      this.$router.push('/')
      return
    }
    ws.addEventListener('open',this.handOpen.bind(this),false)
    ws.addEventListener('close',this.handClose.bind(this),false)
    ws.addEventListener('error',this.handError.bind(this),false)
    ws.addEventListener('message',this.handMessage.bind(this),false)
  },
  methods: {
    sendMsg(){
      let msg = this.msg
      if(!msg.trim().length){
        return
      }
      ws.send(JSON.stringify({
        id:new Date().getTime(),
        user:this.username,
        dateTime:new Date().getTime(),
        msg:this.msg
      }))
      this.msg = ''
    },
    handOpen(e){
      console.log('qian open',e);
    },
    handClose(e){
       console.log('qian close',e);
    },
    handError(e){
       console.log('qian error',e);
    },
    handMessage(e){
       console.log('qian message',e);
      //  console.log(e.data);
       let msg = JSON.parse(e.data)
       this.msgList.push(msg)
    }
  }
}
</script>
